<template>
	<coreshop-page :title="state.isScrollToTop ? '' :userInfoStore.userInfo?.nickName" :placeholder="false"
		titleColor="#fff" mode="left" :bgColor="state.isScrollToTop ? 'rgba(0,0,0,0)':'#d33123'" :isShowStatusBarHeight="false" :isBack="false"
		showLoginModalDom>
		<view class="layout-member-page">
			<view class="member-head">
				<image class="memeber-bg" src="/static/images/member/bg.png"></image>
				<view class="head-box m-b-10">
					<view class="user-info">
						<view class="img-box">
							<image class="img"
								:src="userInfoStore.userInfo?.avatarImage || '/static/images/common/empty.png'">
							</image>
						</view>
						<template v-if="userInfoStore.userInfo && Object.keys(userInfoStore.userInfo).length > 0">
							<view class="info-box">
								<view class="name">{{ userInfoStore.userInfo?.nickName }}</view>
								<view class="price">我的余额：￥{{ userInfoStore.userInfo?.balance || 0 }}</view>
							</view>
							<view class="icon-box"
								@click="handleRouteNavigateTo(`/pages/subpackage/member/set/userInfo/userInfo`)">
								<image class="icon"
									:src="handleStaticResources('/static/images/member/icon-right.png')">
								</image>
							</view>
						</template>
						<template v-else>
							<view class="info-box">
								<view class="login" @click="handleLogin">立即登录</view>
							</view>
						</template>
					</view>
					<view class="user-info-num-box">
						<view class="item" @click="handleJumpPage('/pages/subpackage/member/footprint/footprint')">
							<view class="num">{{ userInfoStore.userInfo?.footPrintCount || 0 }}</view>
							<view class="tit">足迹</view>
						</view>
						<view class="item" @click="handleJumpPage('/pages/subpackage/member/coupon/coupon')">
							<view class="num">{{ userInfoStore.userInfo?.userCouponCount || 0 }}</view>
							<view class="tit">优惠券</view>
						</view>
						<view class="item" @click="handleJumpPage('/pages/subpackage/member/collection/collection')">
							<view class="num">{{ userInfoStore.userInfo?.collectionCount || 0 }}</view>
							<view class="tit">收藏</view>
						</view>
						<view class="item" @click="handleJumpPage('/pages/subpackage/member/afterSales/list/list')">
							<view class="num">{{ state?.afterSaleNums || 0 }}</view>
							<view class="tit">售后</view>
						</view>
					</view>
					<view class="member-box">
						<view class="member-content">
							<view class="content">
								<view class="grade">{{ userInfoStore.userInfo?.gradeName || '普通会员' }}</view>
								<view class="integral">
									我的{{ shopConfigStore?.config?.pointShowName || '积分' }}：{{ userInfoStore.userInfo?.point || 0 }}
								</view>
							</view>
							<view class="view-detail"
								@click="handleJumpPage('/pages/subpackage/member/integral/integral')">
								<text class="tit">查看详情</text>
								<uv-icon name="arrow-right" size="13" color="#292B2E"></uv-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="p-20">
				<!-- 我的订单 -->
				<view class="view-box">
					<view class="title">我的订单</view>
					<view class="order-box p-b-20">
						<view class="item" v-for="item, index in state.orderList" :key="index"
							@click="handleJumpPage(`/pages/subpackage/member/order/list/list?type=${item.orderStatus}`)">
							<image class="img" :src="handleStaticResources(item.img)"></image>
							<view class="name">{{ item.name }}</view>
							<view class="nums" v-if="item.nums && item.nums != 0">{{ item.nums }}</view>
						</view>
					</view>
				</view>
				<!-- 天天有钱 -->
				<view class="view-box" v-if="shopConfigStore.config?.showInviter === ShowInviterEnum.yes">
					<view class="title">天天有钱</view>
					<view class="invitation-box"
						@click="handleJumpPage(`/pages/subpackage/member/invite/invite/invite`)">
						<view class="item">
							<image class="img" :src="handleStaticResources('/static/images/member/invitation-01.png')">
							</image>
							<view class="tit-desc">
								<view class="tit">边逛边赚钱</view>
								<view class="desc">最高提现20元</view>
							</view>
						</view>
						<view class="item" @click="handleJumpPage(`/pages/subpackage/member/invite/invite/invite`)">
							<image class="img" :src="handleStaticResources('/static/images/member/invitation-02.png')">
							</image>
							<view class="tit-desc">
								<view class="tit">邀请好友</view>
								<view class="desc">最高分红50000</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 我的服务 -->
				<view class="view-box">
					<view class="title">我的服务</view>
					<view class="service-box p-b-20">
						<view class="item" v-if="state.userIsClerk?.isClerk"
							@click="handleRouteNavigateTo(`/pages/subpackage/merchant/index/index?storeId=${state.userIsClerk?.storeId}`)">
							<image class="img" :src="handleStaticResources('/static/images/member/icon-form.png')">
							</image>
							<view class="tit">商家管理</view>
						</view>
						<template v-for="item in navState.myServiceList" :key="item.name">
							<view class="item" v-if="item.isShow" @click="handleMyServiceJumpPage(item)">
								<image class="img" :src="handleStaticResources(item.img)"></image>
								<view class="tit">{{ item.title }}</view>
							</view>
						</template>
					</view>
				</view>
				<!-- 增值服务 -->
				<view class="view-box" v-if="shopConfigStore?.config?.showVas === ShowVasEnum.yes">
					<view class="title">增值服务</view>
					<view class="service-box p-b-20">
						<template v-for="item in navState.incrementServiceList" :key="item.name">
							<view class="item" v-if="item.isShow" @click="handleClassifyServiceJumpPage(item)">
								<image class="img" :src="handleStaticResources(item.img)"></image>
								<view class="tit">{{ item.title }}</view>
							</view>
						</template>
					</view>
				</view>
				<!-- 其它服务 -->
				<view class="view-box">
					<view class="title">其它服务</view>
					<view class="service-box p-b-20">
						<template v-for="item in navState.otherServiceList" :key="item.name">
							<view class="item" v-if="item.isShow" @click="handleClassifyServiceJumpPage(item)">
								<image class="img" :src="handleStaticResources(item.img)"></image>
								<view class="tit">{{ item.title }}</view>
							</view>
						</template>
						<!-- #ifdef MP -->
						<view class="item" @click="handleClearCache">
							<image class="img" :src="handleStaticResources('/static/images/member/icon-clear.png')">
							</image>
							<view class="tit">清理缓存</view>
						</view>
						<!-- #endif -->
						<!-- #ifdef APP-PLUS || APP-PLUS-NVUE -->
						<view class="item" @click="handleLogOut">
							<image class="img" :src="handleStaticResources('/static/images/member/icon-logout.png')">
							</image>
							<view class="tit">注销登录</view>
						</view>
						<!-- #endif -->
					</view>
				</view>
			</view>
		</view>
	</coreshop-page>
</template>

<script setup lang="ts">
	import { reactive } from 'vue';
	import { onPageScroll, onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
	import { handleStaticResources, handleRouteNavigateTo, handleShowToast, handleRouteSwitchTab, hanldeShowModal, getDefaultShareData } from '@/core/utils';
	import { queryUserInfo, queryOrderStatusNum, queryUserIsClerk, queryDistributionInfo, queryAgentInfo, queryShopConfigV2 } from '@/core/api';
	import type { Response, MemberOrderType, UserInfoType, UserIsClerkType, MemberServiceType, ShopConfigType } from '@/core/models';
	import { useShopConfigStore, useUserInfoStore, useLoginStore } from '@/core/store';
	import { ShowVasEnum, ShowInviterEnum, OrderTabStatusEnum, MemberPageNameEnum, RouteSwitchTabEnum, DistributionApplyStatus, AgentApplyStatus } from '@/core/enum';
	import { useNavHook } from './use-nav-hook';
	import { UserToken } from '@/core/consts'

	/** 获取项目配置 */
	const shopConfigStore = useShopConfigStore();

	/** 用户数据store */
	const userInfoStore = useUserInfoStore();

	/** 登录store */
	const _useLoginStore = useLoginStore();

	/** 获取服务导航 */
	const { getNav, navState } = useNavHook();
	getNav();

	const state = reactive<{
		orderList : Array<MemberOrderType>;
		afterSaleNums : number;
		userIsClerk : UserIsClerkType,
		isScrollToTop : boolean,
	}>({
		orderList: navState.orderList,
		afterSaleNums: 0,
		userIsClerk: {},
		isScrollToTop: true,
	})

	onPageScroll((e : any) => {
		if (e.scrollTop > 10) {
			state.isScrollToTop = false;
		} else {
			state.isScrollToTop = true;
		}
	})

	onShow(() => {
		if (uni.getStorageSync(UserToken)) {
			getOrderStatusNum();
			getUserInfo();
		}
		shopConfigStore.querySystemConfig();
	});

	/** 获取用户信息 */
	const getUserInfo = async () => {
		const userInfo : Response<UserInfoType> = await queryUserInfo();
		if (userInfo.status) {
			userInfoStore.setUserInfo(userInfo?.data);
			getUserIsClerk();
		} else {
			handleShowToast(userInfo.msg)
		}
	}

	/** 判断用户是否是门店人员 */
	const getUserIsClerk = async () => {
		const userIsClerk : Response<UserIsClerkType> = await queryUserIsClerk();
		state.userIsClerk = userIsClerk.data || {};
	}

	/** 订单各个状态的数量 */
	const getOrderStatusNum = async () => {
		const orderStatusNum : Response<any> = await queryOrderStatusNum({
			ids: [OrderTabStatusEnum.all, OrderTabStatusEnum.pendingPayment, OrderTabStatusEnum.pendingShipment, OrderTabStatusEnum.pendingReceipt, OrderTabStatusEnum.pendingEvaluated].join(','),
			isAfterSale: true
		});
		/** 售后数量 */
		state.afterSaleNums = orderStatusNum?.data?.isAfterSale || 0;
		state.orderList.forEach((item : MemberOrderType) => {
			item.nums = orderStatusNum.data[item.orderStatus] || 0;
		})
	}

	/** 去登录 */
	const handleLogin = () => {
		// #ifdef MP-ALIPAY || MP-WEIXIN
		_useLoginStore.setShowLoginModalTogglePop(true);
		// #endif

		// #ifndef MP-WEIXIN || MP-ALIPAY 
		handleRouteNavigateTo(`/pages/login/login?backUrl=${'/pages/member/member'}`)
		// #endif
	}

	/** 跳转页面 */
	const handleJumpPage = (url : string) => {
		_useLoginStore.checkLogin(() => {
			handleRouteNavigateTo(url);
		});
	}

	/** 我的服务跳转页面 */
	const handleMyServiceJumpPage = (item : MemberServiceType) => {
		_useLoginStore.checkLogin(async () => {
			/** 判断分销  获取分销商进度状态 */
			if (item.name == MemberPageNameEnum.distribution) {
				const info : Response<any> = await queryDistributionInfo();
				if (info.status) {
					if (info.data?.verifyStatus == DistributionApplyStatus.success || (!info.data?.needApply && info.data?.conditionStatus)) {
						handleRouteNavigateTo('/pages/subpackage/distribution/index/index');
					} else if (info.data?.verifyStatus > DistributionApplyStatus.success) {
						handleRouteNavigateTo(`/pages/subpackage/distribution/apply/state`);
					} else {
						handleRouteNavigateTo(`/pages/subpackage/distribution/apply/index`);
					}
				} else {
					handleShowToast(info.msg)
				}
				return;
			}
			/** 判断代理  获取代理商进度状态 */
			if (item.name == MemberPageNameEnum.agent) {
				const info : Response<any> = await queryAgentInfo({ check_condition: true });
				if (info.status) {
					if (info.data?.verifyStatus == AgentApplyStatus.success || (!info.data?.needApply && info.data?.conditionStatus)) {
						handleRouteNavigateTo('/pages/subpackage/agency/index/index');
					} else if (info.data?.verifyStatus > AgentApplyStatus.success) {
						handleRouteNavigateTo(`/pages/subpackage/agency/apply/state`);
					} else {
						handleRouteNavigateTo(`/pages/subpackage/agency/apply/index`);
					}
				} else {
					handleShowToast(info.msg)
				}
				return;
			}
			handleRouteNavigateTo(item.url);
		});
	}

	/** 分类服务跳转页面 */
	const handleClassifyServiceJumpPage = (item : MemberServiceType) => {
		/** 判断签到，系统设置 */
		if (item.name == MemberPageNameEnum.checkIn || item.name == MemberPageNameEnum.setting) {
			_useLoginStore.checkLogin(() => {
				handleRouteNavigateTo(item.url);
			})
		} else {
			handleRouteNavigateTo(item.url);
		}
	}

	/** 清理缓存 */
	const handleClearCache = async () => {
		const shopConfig : Response<ShopConfigType> = await queryShopConfigV2();
		if (shopConfig.status) {
			shopConfigStore.setConfig(shopConfig.data);
            uni.clearStorage();
			handleShowToast('清理成功', 'success', () => {
				setTimeout(() => {
                    uni.reLaunch({
                    	url: '/pages/home/home'
                    });
					// handleRouteSwitchTab(RouteSwitchTabEnum.home)
				}, 1000)
			})
		}
	}

	/** 注销登录 */
	const handleLogOut = () => {
		hanldeShowModal({
			title: "退出",
			content: '确认退出登录吗?',
			async confirmFn() {
				uni.removeStorageSync(UserToken);
				userInfoStore.setUserInfo({});
				handleRouteSwitchTab(RouteSwitchTabEnum.home)
			}
		})
	}

	/** 分享 */
	onShareAppMessage(() => {
		return {
			title: getDefaultShareData().title,
			imageUrl: getDefaultShareData().imageUrl,
			path: 'pages/member/member'
		}
	});
	onShareTimeline(() => {
		return {
			title: getDefaultShareData().title,
			imageUrl: getDefaultShareData().imageUrl,
			path: 'pages/member/member'
		}
	});
</script>

<style lang="scss" scoped>
	@import './member.scss';
</style>